<?php
require_once("include/bittorrent.php");
$seckenuid = $_GET['secken'];
if ($seckenuid == '') {
	stderr("错误", "无效的扫码登录请求");
}
dbconn();
/*
 * 先检查数据库是否存在洋葱ID与站点帐号的绑定
 * 如果有绑定则自动登录
 * 如果没有绑定则进行绑定操作后登录
 */

$res = sql_query("SELECT uid, username FROM seckenapi WHERE secken_uid = '$seckenuid' LIMIT 1");
$binding = mysql_num_rows($res);
if ($binding == 1) {//已经绑定
	failedloginscheck(); //失败登录次数检测
	cur_user_check(); //是否登录检测
	$username = mysql_fetch_array($res);
	//$row = mysql_fetch_array(sql_query("SELECT id, passhash, enabled, status FROM users WHERE username = '" . $username['username'] . "'")); //根据用户名检索
	$row = mysql_fetch_array(sql_query("SELECT id, passhash, enabled, status FROM users WHERE id = '" . $username['uid'] . "'")); //根据用户ID检索
	if ($securelogin == 'yes') {
		$pprefix = "https://";
		$ssl = true;
	} else {
		$pprefix = "http://";
		$ssl = false;
	}
	if ($securetracker == 'yes') {
		$trackerssl = true;
	} else {
		$trackerssl = false;
	}
	$dutime = 86400 * 30; //默认30天时效
	$passh = md5($row["passhash"]);

	if ($row['status'] == 'pending')//判断是否通过验证
		failedlogins("该账户还未通过验证。如果你没有收到验证邮件，试试<a href='confirm_resend.php'><b>重新发送验证邮件</b></a>。");

	if ($row['enabled'] == 'no')//判断是否被封禁
		stderr("登录失败！", "该账号已被禁用。");

	logincookie($row["id"], $passh, 1, $dutime, FALSE, $ssl, $trackerssl);
	if (!empty($_GET["returnto"])) {
		header("Location: " . $pprefix . "$BASEURL/$_GET[returnto]");
		//header("Location: ../$_POST[returnto]");
	} else {
		header("Location: " . $pprefix . "$BASEURL/index.php");
		//header("Location: ../index.php");
	}
} else {
	stdhead("扫码登录");
	?>
	<div>
		<form method="post" action="takebinding.php">
			<table border="0" cellpadding="5" style="margin-top: 20px; margin-bottom: 20px">
				<tr><td class="rowhead"><b style="text-align: end">帐号：</b><input type="text" name="username" /></td></tr>
				<tr><td class="rowhead"><b style="text-align: end">密码：</b><input type="password" name="password" /></td></tr>
				<input type="hidden" name="seckenuid" value="<?= $seckenuid ?>" />
				<input type="hidden" name="returnto" value="<?= $_GET["returnto"] ?>" />
				<tr><td class="rowhead"><input type="submit" name="binding" value="绑定" /></td></tr>
			</table>
		</form>
	</div>
	<?php
}
stdfoot();
